package com.hirsi.common.core.handler;

import cn.hutool.json.JSONUtil;
import com.hirsi.common.core.vo.result.ResponseResult;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * 正确返回数据时进行全局包装
 */
@RestControllerAdvice(basePackages = "com.hirsi")
public class RestResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof HashMap) {
            if (((HashMap) o).get("status") != null) {
                return o;
            }
        } else if (o instanceof ResponseResult) {
            return o;
        } else if (o instanceof String) {
            return JSONUtil.toJsonStr(ResponseResult.success(o));
        }
        return ResponseResult.success(o);
    }
}
